<!--
 * @Author: atao
 * @Date: 2023-11-13 20:01:30
 * @LastEditTime: 2023-12-14 17:01:04
 * @FilePath: \yayun-web000\src\views\login\index.vue
-->
<template>
  <div class="login-container">
    <div class="login-box">
      <div class="title">押韵古装MIS系统</div>
      <div class="content">
        <div class="info" v-show="isPwdLogin">
          <!-- <img src="../../images/bg.jpg" alt=""> -->
          <div class="ipt">
            <el-input placeholder="请输入账号" prefix-icon="el-icon-user-solid" v-model="pwdLoginObj.id">
            </el-input>
          </div>
          <div class="ipt">
            <form action="">
            <el-input placeholder="请输入密码" prefix-icon="el-icon-lock" v-model="pwdLoginObj.password" show-password>
            </el-input></form>
          </div>
          <el-checkbox v-model="remember">是否记住密码？</el-checkbox>
          <el-checkbox v-model="auto">是否同意免登陆？</el-checkbox>
          <el-button type="primary" @click="loginEvt">登录</el-button>

        </div>
        <div :class="['info', canRefresh&&'refresh']" @click="refreshCodeEvt"  v-show="!isPwdLogin">
          <img id="image" src="../../images/white.png" alt="">
        </div>
        <i class="el-icon-s-platform
         taggle" @click="changeEvt"></i>
      </div>
    </div>
    <!-- <Mapi></Mapi> -->
  </div>
</template>
<script>
import Mapi from "@/components/MapContainer.vue"
import { AUTO_CODE_CACHE, JOIN_STR_CACHE, PASSWORD_CACHE, TOKEN_CACHE } from '@/config/common.config'
import { decodeApi, encodeApi, md5Api } from '@/utils';
import { autoCodeApi, autoLoginApi, getMyIconApi, loginApi, menuListApi, qrCodeApi, qrCodeLoopAPI, userInfoApi, userRightsApi } from '@/apis/userApi';
import dayjs from 'dayjs';
import { Collapse } from 'element-ui';
import QRCode from 'qrcode';
export default {
  components: {
    Mapi,
  },
  data() {
    return {
      remember: false,
      auto: false,
      //是否显示登录界面
      isPwdLogin: true,
      //做节流操作
      isGetCode: false,
      //能否刷新
      canRefresh:false,
      codeStr:'',
      codeTimer:null,
      //密码登录对象
      pwdLoginObj: {
        id: '',
        password: ''
      }
    }
  },
  async created() {
   
    //记住密码
    let _cache = localStorage.getItem(PASSWORD_CACHE);
    if (_cache) {
      try {
        _cache = decodeApi(_cache).split(JOIN_STR_CACHE);
        this.pwdLoginObj.id = _cache[0]
        this.pwdLoginObj.password = _cache[1]
        this.remember = true;
      } catch { }
    }
    let _ac = localStorage.getItem(AUTO_CODE_CACHE);
    if (_ac) {
      let _loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      let _res =await autoLoginApi(decodeApi(_ac))
      console.log(_res)
      if(_res.code!==200){
        localStorage.removeItem(AUTO_CODE_CACHE);
        return
      }
      this.auto=true
      let _load=await this.loadInfo(_res)
      _loading.close();
      if(!_load){
        localStorage.removeItem(AUTO_CODE_CACHE);
      }else{
        this.$router.push('/home')
      } 
    }
  },
  methods: {
    /**轮询后端结果 */
    loopResult(_t=1,_count=1){
      this.codeTimer=setTimeout(async () => {
        let _res = await qrCodeLoopAPI(this.codeStr);
        if(_res.code===300){
          if (_count < 5) {
            this.loopResult(_t * 1.5, _count + 1);
          }else{
            this.canRefresh = true
          }
        }else if(_res.code===304){
          this.canRefresh=true
        }else if (_res.code === 200) {
          let _loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          let res= await this.loadInfo(_res)
          _loading.close();
          if(res){
            this.$router.push('/home')
          } else{
            this.canRefresh=true;
          }
        }else{
           this.canRefresh = true
        }
         
      }, _t*1000);
    },
    //刷新二维码方法
    refreshCodeEvt(){
      if(this.canRefresh&&!this.isGetCode){
        this.refreshQrcode()
      }
    },
    //二维码方法
    async refreshQrcode(){
      this.isGetCode = true;
      let _res = await qrCodeApi()
      console.log(_res)
      if (_res.code !== 200) {
        this.isGetCode = false;
        return
      }
      this.codeStr = _res.qrcode;
      var opts = {
        errorCorrectionLevel: 'H',
        type: 'image/jpeg',
        quality: 0.3,
        margin: 1,
        color: {
          dark: "#010599FF",
          light: "#dde2e9"
        }
      }

      QRCode.toDataURL(_res.qrcode, opts
        , (err, url) => {
          this.isGetCode = false;
          if (err) {

          } else {
            this.canRefresh = false;
            var img = document.getElementById('image')
            img.src = url
            this.loopResult()
          }


        })
    },
    //综合验证方法
    loadInfo(result) {
      return new Promise(async resolve => {
        //存token到本地
        sessionStorage.setItem(TOKEN_CACHE, encodeApi(result.token + JOIN_STR_CACHE + Date.now()));
        //存token到状态管理器 后面做对比
        this.$store.commit("setToken", result.token);
        //获取用户信息
        let user = await userInfoApi(result.userid||result.id)
        if (user.code !== 200) {
          this.$message.error("用户登录失败，请重试")
          resolve(false);
          return;
        }
        this.$store.commit("setUserInfo", user.data)
        let rights = await userRightsApi(user.data.role)
        if (rights.code === 200) {
          this.$store.commit("setUserRights", rights.data)
        }
        
        //获取列表
        let menu = await menuListApi()
        if (menu.code === 200) {
          this.$store.commit("setMenuList", menu.data.rows)
        }
        if (this.auto) {
          let res = await autoCodeApi()
          if (res.code === 200) {
            localStorage.setItem(AUTO_CODE_CACHE, encodeApi(res.autocode))
          }
        }
        resolve(true)
      })

    },
    async loginEvt() {
      // let icons = await getMyIconApi();
      // console.log(icons)
    
      if (!this.pwdLoginObj.id) {
        this.$message.error("请输入用户名")
        return
      }
      if (!this.pwdLoginObj.password) {
        this.$message({
          message: '请输入密码',
          type: 'warning'
        })
        return
      }
        let _loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      let result = await loginApi({ id: this.pwdLoginObj.id, password: md5Api(this.pwdLoginObj.password) })
      if (result.code !== 200) {
        this.$message.error("用户登录失败，请重试")
        _loading.close();
        return;
      }
     
      let _load = await this.loadInfo(result);
      if (!_load) {
        _loading.close();
        return
      }
      //记住密码
      if (this.remember) {
        localStorage.setItem(PASSWORD_CACHE, encodeApi(this.pwdLoginObj.id + JOIN_STR_CACHE + this.pwdLoginObj.password));
      } else {
        localStorage.removeItem(PASSWORD_CACHE);
      }
      _loading.close();
      this.$router.push('/home')
    },
    //切换二维码登录
    async changeEvt() {
      if (this.isGetCode) return;
      this.isPwdLogin = !this.isPwdLogin;
      if(!this.isPwdLogin){
           this.refreshQrcode()     
      }else{
        clearTimeout(this.codeTimer)
      }
    }
  }
}
</script>
 
<style lang="less" scoped>
@import "../../style/common.less";

.triangle {
  width: 0;
  height: 0;
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-left: 10px solid;
  border-right: 10px solid transparent;
  // border: 10px solid;
  // border-color: orangered skyblue gold yellowgreen;
}

.login-container {
  .rel();

  >.login-box {
    display: block;
    position: absolute;
    top: 50%;
    left: 50%;
    width: 1030px;
    height: 652px;
    margin-top: -326px;
    margin-left: -515px;

    >.title {
      font-size: 1.2rem;
      font-weight: 600;
      line-height: 50px;
    }

    >.content {
      display: block;
      position: relative;
      width: 100%;
      height: calc(592px - 60px);
      padding-left: 440px;
      overflow: hidden;
      border-radius: 8px;
      box-shadow: 0 0 16px rgba(0, 0, 0, 0.1);

      >.taggle {
        font-size: 18px;
        width: 36px;
        height: 36px;
        line-height: 36px;
        text-align: center;
        position: absolute;
        top: 0;
        right: 0;
        .touch()
      }

      &::before {
        content: '\e899';
        display: block;
        position: absolute;
        top: 0;
        left: 0;
        width: 440px;
        height: 100%;
        background: url(../../images/bg.jpg) center center / 100% 100% no-repeat;
        .iconfont();
      }

      >.info {
        display: block;
        position: relative;
        width: 100%;
        height: 100%;
        padding: 91px 120px 0;
        &.refresh::before{
        content: '\e661';
        display: block;
        position: absolute;
        top: 91px;
        left: 120px;
        text-align: center;
        line-height: 350px;
        width: 350px;
        height: 350px;
        background-color:rgba(0, 0, 0, 0.4); 
        .iconfont(120px, #dde2e9);
        }
        >.ipt {
          line-height: 50px;
          position: relative;

          >.el-input {
            &::before {
              display: block;
              position: absolute;
              top: 0;
              right: 0;
              .iconfont();
              // content: '\e646';
            }
          }
        }

        >img {
          display: block;
          margin: auto;
          width: 350px;
          height: 350px;
        }
      }

    }
  }
}

.el-checkbox {
  display: block;
  margin: 16px 0;
}

.el-button {
  width: 100%;
}
</style>
